//
//  ControlAddressViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/8.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ControlAddressViewController.h"
#import "ControlAddressTableViewCell.h"
#import "AddAddressViewController.h"
static NSString * cellIndentifier = @"ControlAddressTableViewCell";

@interface ControlAddressViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property(nonatomic,strong)NSMutableArray * addressArray;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ControlAddressViewController

- (void)viewWillAppear:(BOOL)animated{
    [self addRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _addressArray = [NSMutableArray array];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.scrollEnabled = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark == 添加地址
- (IBAction)addAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
    page.addressDic = @{};
    [self.navigationController   pushViewController:page animated:YES];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getAddressList];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.addressArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getAddressList];
        });
    }
    
}



- (void)getAddressList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSDictionary * dic1 =  [Common getLoginInfo];
    [dic setObject:dic1[@"userId"] forKey:@"msadMemberId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_GetAddressList withHttpType:@"POST" withTag:SX_SX_AddressList];
    
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 122*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _addressArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ControlAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell= [[ControlAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.personAddress.frame = flexibleFrame(CGRectMake(77, 65, 213, 15), YES);
    cell.personAddress.numberOfLines = 0;
    cell.personAddress.text = _addressArray[indexPath.row][@"msadAddr"];
    [cell.personAddress sizeToFit];
    
    cell.personName.text = _addressArray[indexPath.row][@"msadReceiverName"];
    cell.personPhone.text = _addressArray[indexPath.row][@"msadMobileNo"];
       
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
    page.addressDic = _addressArray[indexPath.row];
    [self.navigationController   pushViewController:page animated:YES];
    

}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==SX_SX_AddressList) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
//                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.addressArray removeAllObjects];
                }
//                NSArray *arr = database[@"result"][@"pageRecord"];
                NSArray *arr = database[@"result"];
                for (id entity in arr) {
                    [self.addressArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
            
            
            
        }
        
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
